package com.walterlife.javacore;

import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;

// commons-daemon.jar download url: http://commons.apache.org/proper/commons-daemon/download_daemon.cgi

public class DaemonProcess implements Daemon {
    private Thread myThread;
    private boolean stopped = false;
    private boolean lastonwasAtick = false;
    
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        myThread = null;
    }

    @Override
    public void init(DaemonContext arg0) throws DaemonInitException, Exception {
        // TODO Auto-generated method stub
        myThread = new Thread(new Runnable() {
            private long lastTick = 0;

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while(!stopped) {
                    long now = System.currentTimeMillis();
                    if(now - lastTick >=1000) {
                        System.out.println(!lastonwasAtick ? "tick" : "tock");
                        lastonwasAtick = !lastonwasAtick;
                        lastTick = now;
                    } 
                } 
            }
        }) {
            @Override
            public synchronized void start() {
                DaemonProcess.this.stopped = false;
                super.start();
            }
        };
    }

    @Override
    public void start() throws Exception {
        // TODO Auto-generated method stub
        if(myThread != null) {
            myThread.start();
        }
    }

    @Override
    public void stop() throws Exception {
        // TODO Auto-generated method stub
        stopped = true;
        myThread.join(1000); 
    }
}
